package com.elin.ch2.tools;

import com.elin.tools.SleepTools;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import java.util.stream.Stream;

public class UseCyclicBarrierTestNew {

    // TODO 模拟Controller体
    public static class Worker2 extends Thread {


        public ThreadLocal<Map<String, Supplier<?>>> map;

        // 尝试不安全的线程执行方法（没有意义，传递进来的参数赋值，拿到了对应的堆地址，所以并非不安全，在传递进来的参数是安全的情况下）
        public Map<String, Supplier<?>> noSafeMap;

        // TODO 得出结论，在构造方法拿到的数据赋值给成员方法，并非不安全。只要确保上游数据是安全即可

        public UseCyclicBarrierNew useCyclicBarrierNew;

        /**
         *
         * @param useCyclicBarrierNew 模拟调用bean方法useCyclicBarrierNew,
         * @param map 模拟tomcat传递对应的值到对应的controller对应方法
         */
        public Worker2(UseCyclicBarrierNew useCyclicBarrierNew, Map<String, Supplier<?>> map) {
            this.map = ThreadLocal.withInitial(() -> map);
            this.noSafeMap = map;
            this.useCyclicBarrierNew = useCyclicBarrierNew;
        }

        // TODO 模拟controller对应的方法
        @Override
        public void run() {
            String name = Thread.currentThread().getName();
            // TODO 模拟在controller方法内调用bean对象里的useCyclicBarrierNew方法,并传递tomcat的值到方法中,并使用方法start()
            useCyclicBarrierNew.setParame(map.get());
            Map<String, Object> runner = useCyclicBarrierNew.start();

            //测试代码
            TreeMap<String, Object> stringObjectTreeMap = new TreeMap<>(runner);
            System.out.println("Threadname = " + name + stringObjectTreeMap);
        }
    }

    public static void main(String[] args) {
        // TODO 在单线程下确保所有子线程都使用同一块资源 Map
        // TODO 模拟在ssm模式下，useCyclicBarrierNew被bean收录
        UseCyclicBarrierNew useCyclicBarrierNew = new UseCyclicBarrierNew();
        // TODO 模拟在多线程下调用useCyclicBarrierNew方法。
        int ThreadNum = 10;
        int MapNum = 10;
        int[][] result = new int[ThreadNum][MapNum];
        for (int i = 0; i < ThreadNum; i++) {
            Random random = new Random();
            Map<String, Supplier<?>> map = new HashMap<>();
            for (int j = 0; j < MapNum; j++) {
                int finalI = i;
                int finalJ = j;
                map.put("mycat-"+i+"-"+j, () -> {
                    SleepTools.second(1);
                    int i1 = random.nextInt(10000);
                    result[finalI][finalJ] = i1;
                    return i1;
                });
            }
            new Thread(new Worker2(useCyclicBarrierNew,map), "index-"+i).start();
        }

        SleepTools.second(2);
        Stream.of(result).forEach(r -> System.out.println(Arrays.toString(r)));
        System.out.println();

    }
}
